package com.cda.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cda.mall.entity.ProductComments;
import com.cda.mall.dao.ProductCommentsMapper;
import com.cda.mall.entity.ProductCommentsVO;
import com.cda.mall.service.IProductCommentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cda.mall.utils.PageHelper;
import com.cda.mall.vo.ResStatus;
import com.cda.mall.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 商品评价  服务实现类
 * </p>
 *
 * @author cda
 * @since 2021-11-13
 */
@Service
public class ProductCommentsServiceImpl extends ServiceImpl<ProductCommentsMapper, ProductComments> implements IProductCommentsService {

    @Autowired
    private ProductCommentsMapper productCommentsMapper;

    @Override
    public ResultVO listCommentsByProductId(String productId,int pageNum,int limit) {
//        List<ProductCommentsVO> productCommentsVOS = productCommentsMapper.selectCommentsByProductId(productId);
        //根据商品id查询总记录数
        int count = productCommentsMapper.selectAll(productId);

        //计算总页数（必须确定每页显示多少条  pageSize:limit）
        int pageCount = count%limit==0 ? count/limit : count/limit+1;

        //查询当前页的数据(评论中需要用户信息，因此需要连表查询===自定义)
        int start = (pageNum-1)*limit;
        List<ProductCommentsVO> list = productCommentsMapper.selectCommentsByProductId(productId, start, limit);

        return new ResultVO(ResStatus.OK,"success",new PageHelper<ProductCommentsVO>(count,pageCount,list));
    }

    @Override
    public ResultVO getCommentCountByProductId(String productId) {
        //1.查询当前商品评价的总数
        int total = productCommentsMapper.selectAll(productId);
        QueryWrapper wrapper = new QueryWrapper();
        QueryWrapper wrapper1 = new QueryWrapper();
        QueryWrapper wrapper2 = new QueryWrapper();
        //查询好评数
        wrapper.eq("comm_type",1);
        Long goodtotal = productCommentsMapper.selectCount(wrapper);
        //查询中评数
        wrapper1.eq("comm_type",0);
        Long midtotal = productCommentsMapper.selectCount(wrapper1);
        //查询差评数
        wrapper2.eq("comm_type",-1);
        Long badtotal = productCommentsMapper.selectCount(wrapper2);

        //计算好评率
        double percent = (Double.parseDouble(goodtotal+"")/Double.parseDouble(total+""))*100;
        String percentValue = (percent+"").substring(0,(percent+"").lastIndexOf(".")+3);

        HashMap<String ,Object> map = new HashMap<>();
        map.put("total",total);
        map.put("goodtotal",goodtotal);
        map.put("midtotal",midtotal);
        map.put("badtotal",badtotal);
        map.put("persent",percentValue);
        return new ResultVO(ResStatus.OK,"success",map);
    }


}
